package com.data.modules.message.websocket;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.data.common.base.BaseMap;
import com.data.common.constant.CommonSendStatus;
import com.data.common.constant.WebsocketConst;
import com.data.common.modules.redis.listener.BootRedisListerer;
import com.data.modules.message.entity.SysMessage;
import com.data.modules.message.handle.enums.SendMsgStatusEnum;
import com.data.modules.message.service.ISysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听消息(采用redis发布订阅方式发送消息)
 */
@Slf4j
@Component
public class SocketHandler implements BootRedisListerer {
    @Autowired
    private ISysMessageService sysMessageService;
    @Autowired
    private WebSocket webSocket;

    @Override
    public void onMessage(BaseMap map) {
        log.info("onMessage【SocketHandler消息】Redis Listerer:" + map.toString());

        String userId = map.get("userId");
        String message = map.get("message");
        if (ObjectUtil.isNotEmpty(userId)) {
            boolean flag = webSocket.pushMessage(userId, message);
            //是用户信息则 标识为失败 待重新推送
            if(!flag){
                JSONObject msg = JSONObject.parseObject(message);
                if(ObjectUtil.isNotEmpty(msg.getString(WebsocketConst.CMD_USER))
                        && ObjectUtil.isNotEmpty(msg.getString(WebsocketConst.MSG_ID))){

                    String msgId = msg.getString(WebsocketConst.MSG_ID);
                    SysMessage sysMessage = sysMessageService.getById(msgId);
                    if(sysMessage != null){
                        sysMessage.setEsSendNum(sysMessage.getEsSendNum() + 1);
                        sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode());
                        // 发送结果回写到数据库
                        sysMessageService.updateById(sysMessage);
                    }
                }
            }
            //app端消息推送
            //webSocket.pushMessage(userId+ CommonSendStatus.APP_SESSION_SUFFIX, message);
        } else {
            webSocket.pushMessage(message);
        }

    }
}